<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Accounts extends T3WD_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */

	public function Accounts()
	{
		 parent::__construct();		 
		 $this->load->helper('form');
		 
		 $name_module = 'usuario';
		if($name_module!==$this->session->userdata('name_module')){
			$this->session->set_userdata('name_module', $name_module);
			$this->session->set_userdata('userSort', 0);
			$this->session->set_userdata('userDirection', 0);
			$this->session->set_userdata('userCount', 0);	
			$this->session->set_userdata('search', '');

		}
		
	}	 
	
/////////////////////////////metodos de autenticacion en el sistema////////////////////////////////////////	 
	public function index()
	{
		$this->login();
	}
///////////////////////////////////////////////////////////////////////////////////////////////////////////	
	public function login(){
		$this->_load_data();	

		$this->data_view['_REDIRECT_TO'] = $this->input->get_post('redirectTo');
		$this->data_view['_HEADER_TITLE'] = 'Welcome';
		$this->load->view('login', $this->data_view);
	}
	public function proccess_login(){
		
		//inicializacion
		$this->load->library('PasswordHash');
		$this->load->model('usuarios_model');
		 $this->load->library('session');
		
		$login = $this->input->post('login');
		$pass_post = $this->input->post('pass');
		
		$pass_db = $this->usuarios_model->get_password_by_login($login);
		

		if ($pass_db){
			
				$wp_hasher = new PasswordHash();					

				if ($wp_hasher->CheckPassword($pass_post, $pass_db)){
					//usuario autenticado	
					$this->_create_session($login);
					$redirect = $this->input->get_post('redirectTo');
					if( !empty($redirect)){
						redirect($redirect);
					}
					redirect('home');
				} else {
					//password erroneo
					$this->session->set_flashdata('error', 'Usuario o password incorrectos');				
					redirect('accounts/login');
				}
		} else {
			//no existe el usuario
			$this->session->set_flashdata('error', 'Usuario o password incorrectos');							
			redirect('accounts/login');
		}
	


	}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////	

	function logout()
	{		 
		$this->_destroy_session();
		redirect('accounts');
	}
///////////////////////////////metodos de modulo////////////////////////////////////////////////////////////////	
		public function view()
	{
		$this->_only_authorized_personnel();	
		$this->data_view['_HEADER_TITLE'] = 'Usuarios';
		$this->data_view['_message_error'] = $this->session->flashdata('error');
		$this->data_view['_message_sucessfully'] = $this->session->flashdata('sucessfully');
		
		//inicializacion
		$this->load->library('pagination');
		$this->load->helper('sort');
		$this->load->helper('string');		
		$this->load->model('usuarios_model');
		
		//variables del buscador	
		if ($this->input->post('search_post')){
			
		$search = $this->input->post('search');				
			$this->session->set_userdata('search', $search);
		} 		

		$this->data_view['search_value'] = $this->session->userdata('search');			
		
		$post_search = $this->input->post('search');
		$search_post = $this->input->post('search_post');
		$session_search = $this->session->userdata('search');


		//variables del ordenador
		$sort = $this->session->userdata('userSort');
		$direction = $this->session->userdata('userDirection');
		$perPage = $this->session->userdata('userCount');		

		if(!$perPage)
		{
			$perPage = 6;
			$this->session->set_userdata('userCount', $perPage);
		}			

		if(!$sort)
		{
			$sort = 'id_usuario';
			$this->session->set_userdata('userSort', $sort);
		}

		if(!$direction)
		{
			$direction = 'desc';
			$this->session->set_userdata('userDirection', $direction);
		}


		$this->data_view['sort'] = $sort;
		$this->data_view['direction'] = $direction;
		$this->data_view['perPage'] = $perPage;				

		//configuracion del paginador
		$config['base_url'] = base_url().index_page().'/accounts/view/pagina';
		$config['total_rows'] = $this->usuarios_model->getNumUsers();
		$config['per_page'] = $perPage;	
		$config['uri_segment'] = 4;	
		
		$config['num_links'] = 1;
		$config['next_link'] = '<div class="page-right"></div>';
		$config['last_link'] = '<div class="page-far-right"></div>';
		$config['prev_link'] = '<div class="page-left"></div>';
		$config['first_link'] = '<div class="page-far-left"></div>';
		$config['num_tag_open'] = '<div id="page-info">';
		$config['num_tag_close'] = '</div>';
		$config['cur_tag_open'] = '<div id="page-info"><strong>';
		$config['cur_tag_close'] = '</strong></div>';		
		
		$this->pagination->initialize($config);		

		$this->data_view['users'] = $this->usuarios_model->getAllUsers($sort, $direction, $perPage, $this->uri->segment(4));	

		$this->data_view['pagination'] = $this->pagination->create_links();
		$this->data_view['pagina'] = $this->uri->segment(4);
		$this->data_view['numberPagina'] = $this->uri->segment(4) + 1;

		
		$this->load->view('accounts', $this->data_view);
	}
	
	
		public function sort()
	{
		$this->_only_authorized_personnel();	
		if($this->input->post('sort'))	{
			$sort = $this->input->post('sort');
			$this->session->set_userdata('userSort', $sort);
		}		

		if($this->input->post('direction'))	{
			$direction = $this->input->post('direction');
			$this->session->set_userdata('userDirection', $direction);
		}
		
		redirect('accounts/view');
	}
	
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
		public function add()
	{
		//inicializacion
		$this->_only_authorized_personnel();	
		$this->data_view['_HEADER_TITLE'] = 'Usuarios';
		$this->load->model('usuarios_model');
		$this->load->helper('url');
		$this->load->library('form_validation');
		
		

		//valido el formulario
		$this->form_validation->set_rules('nombre', 'Nombre', 'xss_clean|required|trim');
		$this->form_validation->set_rules('login', 'login', 'trim|required|min_length[1]|max_length[120]|xss_clean|callback__validation_unique_name');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[120]|xss_clean|matches[password_repeat]');
		$this->form_validation->set_rules('password_repeat', 'Repetir password', 'trim|required');
		$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
		$this->form_validation->set_rules('tipo_usuario', 'Tipo de usuario', 'trim');
		$this->form_validation->set_rules('status', 'Estatus', 'trim');
		
		$this->form_validation->set_error_delimiters('<div class="error-left"></div>
			<div class="error-inner">', '</div>');

		if ($this->form_validation->run() == TRUE)
		{
			//traigo los datos
			$nombre = $this->input->post('login');
		    $login = $this->input->post('login');
			$password = $this->input->post('password');
			$email = $this->input->post('email');
			$tipo_usuario = $this->input->post('tipo_usuario');
			$status = $this->input->post('status');
			
			//encripto el password
			$this->load->library('PasswordHash');
			$wp_hasher = new PasswordHash();
	 		$password_wp = $wp_hasher->HashPassword($password);	
			
			//realizo la insercion
			$id_usuario = $this->usuarios_model->set_row_usuarios($nombre,$login,$password_wp,$email,$tipo_usuario,$status);			
			
			//redirecciono
			if ($id_usuario)
				$this->session->set_flashdata('sucessfully', 'Usuario '.$login.' creado satisfactoriamente');
			else 
				$this->session->set_flashdata('error', 'Error. No se pudo crear el usuario '.$login);
			
			redirect('accounts/view');
			
		}
		else
		{
			$this->load->view('addUser', $this->data_view);
		}
		
	}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
		public function update()
	{
		//inicializacion
		$this->_only_authorized_personnel();	
		$this->data_view['_HEADER_TITLE'] = 'Usuarios';
		$this->load->model('usuarios_model');
		$this->load->helper('url');
		$this->load->library('form_validation');
		
		
		//redirecciono en caso de cancelar
		$cancel = $this->input->post('cancel');
		if (!empty($cancel))
			redirect('accounts/view');
		
		//obtengo el id de usuario
		$id_usuario = ($this->input->post('id_usuario'))?$this->input->post('id_usuario'):$this->uri->segment(3);
		
		//valido el formulario
		$this->form_validation->set_rules('nombre', 'Nombre', 'xss_clean|required|trim');		
		$this->form_validation->set_rules('password', 'Password', 'trim|min_length[6]|max_length[120]|xss_clean|matches[password_repeat]');
		$this->form_validation->set_rules('password_repeat', 'Repetir password', 'trim');
		$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
		$this->form_validation->set_rules('tipo_usuario', 'Tipo de usuario', 'trim');
		$this->form_validation->set_rules('status', 'Estatus', 'trim');
		
		$this->form_validation->set_error_delimiters('<div class="error-left"></div>
			<div class="error-inner">', '</div>');

		if ($this->form_validation->run() == TRUE)
		{
			//traigo los datos
			$nombre = $this->input->post('nombre');
		    $login = $this->input->post('login');
			$password = $this->input->post('password');
			$email = $this->input->post('email');
			$tipo_usuario = $this->input->post('tipo_usuario');
			$status = $this->input->post('status');
			
			//realizo la actualizacion
			$updated = $this->usuarios_model->set_nombre($id_usuario,$nombre);
			$updated = $this->usuarios_model->set_email($id_usuario,$email);
			$updated = $this->usuarios_model->set_tipo_usuario($id_usuario,$tipo_usuario);
			$updated = $this->usuarios_model->set_estatus_usuario($id_usuario,$status);
			
			//actualizo el password de ser necesario
			if (!empty($password)){
				
				//encripto el password
				$this->load->library('PasswordHash');
				$wp_hasher = new PasswordHash();
				$password_wp = $wp_hasher->HashPassword($password);
				
				$updated = $this->usuarios_model->set_password($id_usuario,$password_wp);
			}		
			
			//redirecciono
			if ($updated)
				$this->session->set_flashdata('sucessfully', 'Usuario '.$login.' actualizado satisfactoriamente');
			else 
				$this->session->set_flashdata('error', 'Error. No se pudo actualizar el usuario '.$login);
			
			redirect('accounts/view');
			
		}
		else
		{
			//busco los datos asociados			
			$arrayUsuario = $this->usuarios_model->get_row_user($id_usuario);
			
			$this->data_view['id_usuario'] = $id_usuario;	
			$this->data_view['nombre'] = $arrayUsuario['nombre'];
			$this->data_view['login'] = $arrayUsuario['login'];
			$this->data_view['email'] = $arrayUsuario['email'];
			$this->data_view['tipo_usuario'] = $arrayUsuario['tipo_usuario'];
			$this->data_view['status'] = $arrayUsuario['status_usuario'];
			
			$this->load->view('updateUser', $this->data_view);
		}
		
	}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	
	public function delete(){
				
		$this->_only_authorized_personnel();	
		$this->load->model('usuarios_model');
		$deleted = $this->usuarios_model->delete_user($this->uri->segment(3));
		
		//redirecciono
		if ($deleted)
			$this->session->set_flashdata('sucessfully', 'Usuario eliminado');
		else 
			$this->session->set_flashdata('error', 'Error. No se pudo eliminar el usuario');
		
		$url_paginador = ($this->uri->segment(4)=='pagina')?'/pagina/'.$this->uri->segment(5):'';
		redirect('accounts/view'.$url_paginador);		
	}
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	

	public function ajax()
	{
		if(!$this->_is_loggin()){
			return '';
		} else {
			//... ...
			return '{value:listo}';
		}
	}
	
	/*public function _pass(){
		$this->load->library('PasswordHash');
		$wp_hasher = new PasswordHash();
	 $password_wp = $wp_hasher->HashPassword('lacalaca');	
	 echo "($password_wp)";
		
	}*/
	
	// Funciones auxiliares
// ------------------------------------------------------------------------
	/*
	 * Establece las variebles de sesion necesarias
	 */
	function _create_session($login)
	{
		
		$id_usuario = $this->usuarios_model->get_id_usuario_by_login($login);
		
		/* Variable pivote para identificar logueo a nivel de sistema */
		$this->session->set_userdata('login', TRUE);

		/* Informacion adicional del usuario */
		$this->session->set_userdata('id',$id_usuario);
		$this->session->set_userdata('nombres',
				$this->usuarios_model->get_nombre($id_usuario));
		$this->session->set_userdata('email',
				$this->usuarios_model->get_email($id_usuario));
		$this->session->set_userdata('tipo_usuario',
				$this->usuarios_model->get_tipo_usuario($id_usuario));
		$this->session->set_userdata('lang',
				$this->usuarios_model->get_lang($id_usuario));
		$this->session->set_userdata('login',$login);
	}
	
	/*
	 * Destruye las variables de sesion.
	 */
	function _destroy_session()
	{
		$this->session->sess_destroy();
	}
	
	
	// funcion de validacion de no existencia de usuario
	function _validation_unique_name($str)
	{
		$id_usuario = $this->usuarios_model->get_id_usuario_by_login($str);
		
		if ($id_usuario){
			$this->form_validation->set_message('_validation_unique_name', 'El usuario <strong>'.$str.'</strong> ya existe en la base de datos');
			return FALSE;
		} else	{
			return TRUE;
		}
	}

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */